package com.yc.store.servlet;

import com.google.gson.Gson;
import com.yc.store.bean.Result;
import com.yc.store.bean.User;
import com.yc.store.biz.BizExeption;
import com.yc.store.biz.UserBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        WebApplicationContext ioc=
                WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
        resp.setContentType("application/json;charset=utf-8");
        UserBiz userBiz = ioc.getBean(UserBiz.class);
        String pwd = req.getParameter("pwd");
        String repwd = req.getParameter("repwd");
        String name = req.getParameter("username");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");

        User user = new User(null,name,pwd,  phone, email );
        Result result;
        try {
            result = userBiz.test(user, repwd);
        } catch (BizExeption e) {
            result = new Result(0, "错误， 请联系管理员", null);
        }

        Gson gson = new Gson();
        if(result.getCode() == 0){
            String json = gson.toJson(result);
            resp.getWriter().print(json);
            return;
        }

        String json = gson.toJson(result);
        resp.getWriter().print(json);



    }
}
